package net.azure.app.util;

import net.azure.app.model.Risk;

import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: Venkatraman Kandaswamy : kvenkatraman@gmail.com
 * Date: 27-Jul-2008
 * Time: 15:51:02
 */
public class Reflector {
    public static void copyValuesFromTo(Object srcObject, Object destObject, String modifier1, String modifier2) {
        Method[] allMethods = srcObject.getClass().getDeclaredMethods();
        for (Method method : allMethods) {
            String methodName = method.getName();
            if(methodName.startsWith("get")){
                try {
                    Object value = method.invoke(srcObject,null);
                    Method destMethod = destObject.getClass().getDeclaredMethod("get" + methodName.substring(3, methodName.length()) + modifier1, null);
                    Object o = destMethod.invoke(destObject, null);
                    Class whatClass = (value instanceof String ) ? String.class : Object.class;
                    Method finalMethod = o.getClass().getMethod("set" + modifier2,whatClass);
                    finalMethod.invoke(o,value);
                } catch (IllegalAccessException e) {
                    System.out.println(e);
                } catch (InvocationTargetException e) {
                    System.out.println(e);
                } catch (NoSuchMethodException e) {
                    System.out.println(e);
                } catch(ClassCastException e){
                    System.out.println(e);
                }
            }
        }
    }

    public static List<Method> getMethods(Object introspectObj, Object destObj, String modifier) {
        List<Method> methods = new ArrayList<Method>();
        Method[] allMethods = introspectObj.getClass().getDeclaredMethods();
        for (Method method : allMethods) {
            String methodName = method.getName();
            if(methodName.startsWith("get")){
                try {
                    Method destMethod = destObj.getClass().getDeclaredMethod("get" + methodName.substring(3, methodName.length()) + modifier, null);
                    methods.add(destMethod);
                } catch (NoSuchMethodException e) {
                }
            }
        }
        return methods;
    }
}
